from django.shortcuts import redirect
from django.contrib import messages
from django.urls import reverse
from django.contrib.auth import logout

class UserBanMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 检查用户是否已登录且被封禁
        if request.user.is_authenticated and not request.user.is_staff and not request.user.is_superuser:
            try:
                profile = request.user.profile
                if profile.is_banned:
                    # 如果用户被封禁，首先注销用户
                    ban_reason = profile.ban_reason or "违反社区规则"
                    logout(request)
                    # 显示封禁消息
                    messages.error(request, f"您的账号已被封禁，原因：{ban_reason}。如有疑问，请联系管理员。")
                    return redirect('user:login')
            except Exception:
                # 如果获取用户资料出错，继续处理请求
                pass

        response = self.get_response(request)
        return response 